import gtk.gdk
import StringIO
from gtk import *
import Image as PIL
from xml.sax.saxutils import escape
from os.path import basename
from urllib2 import url2pathname


CACHE = "cache"
THUMBNAILS_SIZE = 48

def save_thumbnail(string, fname):
    image = PIL.open(StringIO.StringIO(string))
    image.thumbnail((THUMBNAILS_SIZE, THUMBNAILS_SIZE), PIL.ANTIALIAS)
    image.save(fname, "JPEG")

def make_markup(url, title="", artist="", album=""):
    if not title:
        _url = url.replace("+", " ")
        path = url2pathname(_url)
        _basename = escape(basename(path))
        return basename(_basename)
    _title = escape(title)
    _artist = escape(artist)
    _album = escape(album)
    first_line = _title
    second_line = "".join(["<i>", _artist,"</i>"])
    third_line = "".join(["<i>", _album,"</i>"])
    markup = "\n".join([first_line, second_line, third_line])
    return markup

#TODO: A good isbold method

def bold(markup):
    bold_markup = "".join(['<span weight="bold">', markup, "</span>"])
    return bold_markup
    
def unbold(markup):
    markup.strip()
    head, sep, tail = markup.partition('<span weight="bold">')
    unbold_markup, sep, tail = tail.partition('</span>')
    return unbold_markup

def configure_progressbar(aidem):
    aidem.progressbar_pressed = False

def build_playlist(aidem):
    model = ListStore(gtk.gdk.Pixbuf, str, int, bool)
    treeview = aidem.get_widget("treeview1")
    treeview.set_model(model)
    treeview.set_headers_visible(True)
    selection = treeview.get_selection()
    selection.set_mode(SELECTION_MULTIPLE)
    info = CellRendererText()
    cover = CellRendererPixbuf()
    column = TreeViewColumn("<-Slide to show more controls->")
    column.pack_start(cover, expand=False)
    column.pack_start(info)
    column.add_attribute(cover, "pixbuf", 0)
    column.add_attribute(info, "markup", 1)
    column.set_visible(True)
    treeview.append_column(column)
    

